<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>背景图</title>
</head>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
  <script>
    /**
     * 绘制背景图
     * createPattern(image, repeat): 在指定的方向上重复指定的图像
     * image: 规定要使用的图像、画布或视频元素
     * repeat: repeat, repeat-x, repeat-y, no-repeat
     * repeat: repeat: 重复图像
     * repeat-x: 水平重复图像
     * repeat-y: 垂直重复图像
     * no-repeat: 不重复图像
    */
    const myCanvas = document.getElementById("myCanvas");
    const ctx = myCanvas.getContext("2d");

    let img = new Image();
    img.src = "https://www.runoob.com/try/demo_source/paris.jpg";
    img.onload = function() {
      let ptrn = ctx.createPattern(img, "repeat");
      ctx.rect(0, 0, 200, 200);
      ctx.fillStyle = ptrn;
      ctx.fill();
    }
  </script>
</body>
</html>